package com.sugree.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONObject;
import org.json.JSONException;

import android.util.Log;

public class Bitly implements Shortener {
	private static final String TAG = "Bitly";

	private static final String BASE_URL = "http://api.bit.ly/v3/";

	private String mLogin;
	private String mKey;
	private String mXLogin;
	private String mXKey;

	public Bitly(String login, String key) {
		mLogin = login;
		mKey = key;
	}

	public Bitly(String login, String key, String xlogin, String xkey) {
		mLogin = login;
		mKey = key;
		mXLogin = xlogin;
		mXKey = xkey;
	}

	@Override
	public String shorten(String url) throws ApiException {
		try {
			StringBuffer buf = new StringBuffer();
			buf.append(BASE_URL);
			buf.append("shorten?login=");
			buf.append(URLEncoder.encode(mLogin, "UTF-8"));
			buf.append("&apikey=");
			buf.append(URLEncoder.encode(mKey, "UTF-8"));
			if (mXLogin != null && mXKey != null) {
				buf.append("&x_login=");
				buf.append(URLEncoder.encode(mLogin, "UTF-8"));
				buf.append("&x_apiKey=");
				buf.append(URLEncoder.encode(mKey, "UTF-8"));
			}
			buf.append("&longUrl=");
			buf.append(URLEncoder.encode(url, "UTF-8"));
			buf.append("&format=json");
			Log.d(TAG, buf.toString());
			String response = DownloadTasks.getUrlContent(buf.toString());
			JSONObject jo = new JSONObject(response);
			if (jo.getInt("status_code") != 200) {
				throw new Shortener.ApiException(jo.getString("status_txt"));
			}
			JSONObject data = jo.getJSONObject("data");
			return data.getString("url");
		} catch (UnsupportedEncodingException e) {
			throw new Shortener.ApiException(e);
		} catch (IOException e) {
			throw new Shortener.ApiException(e);
		} catch (JSONException e) {
			throw new Shortener.ApiException(e);
		} catch (Shortener.ApiException e) {
			throw e;
		} catch (Exception e) {
			throw new Shortener.ApiException(e);
		}
	}
}
